package main

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/mount"
	"github.com/docker/docker/client"
	"github.com/docker/go-connections/nat"
	"io/ioutil"
	"log"
	"time"
)

var (
	cli *client.Client
)
// 调用docker api 展示 docker 创建容器的能力.
func init() {
	cli, _ = client.NewEnvClient()
}
func main() {
	name := "createContainerSimple"
	forceRemove(name)
	createContainerSimple(name)
	//stopContainer()
	//name2 := "createContainerSimple2"
	//createContainerSimple(name2)
	//removeOldContainer()
	//renameNewContainer()
}

func forceRemove(containerName string) {
	var localContainer *types.Container
	cs, _ := cli.ContainerList(context.Background(), types.ContainerListOptions{
		All: true,
	})
	for _, c := range cs {
		for _, n := range c.Names {
			if n[1:] == containerName {
				localContainer = &c
				break
			}
		}
		if localContainer != nil {
			break
		}
	}

	t := 5 * time.Second
	if localContainer != nil {

		body, err := cli.ContainerStats(context.Background(), localContainer.ID, false)

		fmt.Println(body.OSType)

		b, _ := ioutil.ReadAll(body.Body)

		fmt.Println(string(b))

		cli.ContainerStop(context.Background(), localContainer.ID, &t)
		err = cli.ContainerRemove(context.Background(), localContainer.ID, types.ContainerRemoveOptions{})

		fmt.Println(err)
	}
}

func pauseContainer() {

	err := cli.ContainerPause(context.Background(), "createContainerSimple")

	fmt.Println(err)
}

func stopContainer() {
	t := 5 * time.Second
	err := cli.ContainerStop(context.Background(), `createContainerSimple`, &t)

	fmt.Println("stop ",err)
}

func removeOldContainer() {
	err := cli.ContainerRemove(context.Background(), `createContainerSimple`, types.ContainerRemoveOptions{})
	fmt.Println("removeOldContainer  ",err)
}

func renameNewContainer() {
	err := cli.ContainerRename(context.Background(), "createContainerSimple2", "createContainerSimple")
	fmt.Println("renameNewContainer  ",err)
}

func createContainerSimple(name string) {

	cfg := &container.Config{
		Hostname:        "",
		Domainname:      "",
		User:            "",
		AttachStdin:     false,
		AttachStdout:    false,
		AttachStderr:    false,
		Tty:             false,
		OpenStdin:       false,
		StdinOnce:       false,
		Env:             []string{"FOO=1","BAR=2"},
		Healthcheck:     nil,
		ArgsEscaped:     false,
		Image:           "main:latest",
		WorkingDir:      "",
		Entrypoint:      nil,
		NetworkDisabled: false,
		MacAddress:      "",
		OnBuild:         nil,
		Labels:          nil,
		StopSignal:      "",
		StopTimeout:     nil,
		Shell:           nil,
		ExposedPorts:    nat.PortSet{"8080": struct{}{}}, // export port!
	}

	hcfg := &container.HostConfig{
		Links: nil,
		Mounts: []mount.Mount{
			{
				Type:   mount.TypeBind,
				Source: "/Users/mrj/Desktop/gogsci/examples",
				Target: "/data",
			},
		},
		PortBindings: map[nat.Port][]nat.PortBinding{nat.Port("8080"): {{HostIP: "127.0.0.1", HostPort: "8080"}}},
	}

	body, err := cli.ContainerCreate(context.Background(), cfg, hcfg, nil, name)
	if err != nil {
		log.Fatal(err)
	}

	err = cli.ContainerStart(context.Background(), body.ID, types.ContainerStartOptions{})
	if err != nil {
		log.Fatal(err)
	}

	rc, err := cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Details:    true,
	})
	if err != nil {
		log.Fatal(err)
	}

	defer rc.Close()

	b, _ := ioutil.ReadAll(rc)

	fmt.Println(string(b))
}
